#将pdf分块处理

import pymupdf
import csv
import requests
import base64
from time import sleep
def tup_shibie(img_url):
    '''
    网络图片文字识别
    '''

    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/webimage"
    # 二进制方式打开图片文件
    f = open(img_url, 'rb')
    img = base64.b64encode(f.read())
    access_token="24.9dedfeeda60c7bd78eb435c68a431539.2592000.1756989198.282335-119699574"
    params = {"image":img}
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    sleep(1)
    if response:
        content = response.json()
        print(content)
        # 提取所有words内容
        words_list = [item['words'] for item in content['words_result']]

        # 打印结果
        # print(words_list)
        str_max = ''
        for i in words_list:
            str_max += " " + i
        return str_max

i = input("是否需要创建csv文件接收数据（是输入1：否输入0）追加模式（0）创建模式（1）：")
if i == '1':
    f = open('grxx.csv', 'w',encoding="utf-8", newline='')  #将文件打开
    csv_Writer = csv.writer(f,dialect='excel')
    model_list =['基础信息','职业潜能','价值观排序','个人风格','个人动机','优势才干','职业角色','个人认知']
    csv_Writer.writerow(model_list)
else:
    f = open('grxx.csv','a',encoding="utf-8", newline='')
    csv_Writer = csv.writer(f,dialect='excel')
'''如果需要批量处理就需要将pdf_file_name转化为列表'''
pdf_file_name = []  # pdf文件路径
num_ = input("请输入你要导入文件的数量 ：")
for i in range(int(num_)):
    file_name = input(f"请输入第{i}个要处理的文件名例子（刘宇航-数据报告-20250712.pdf）：")
    pdf_file_name.append(file_name)
def splie_pdf(pdf_file_name):
    #切片处理：将pdf进行切片操作让对应的部分文字提取更加准确
    clip1 = pymupdf.Rect((400,0), (800, 80))  # 截图的左上角及右下角坐标，根据实际情况修改
    clip2 = pymupdf.Rect((60,155), (800, 280))
    clip2_1 = pymupdf.Rect((60,280), (800, 350))
    # clip2_2 = pymupdf.Rect((50,284), (800, 350))
    clip3 = pymupdf.Rect((0,385), (385, 600))
    clip4 = pymupdf.Rect((385,385), (800, 600))
    clip5 = pymupdf.Rect((0,650), (385, 800))
    clip6 = pymupdf.Rect((385,650), (590, 800))
    clip7 = pymupdf.Rect((0,830), (385, 1000))
    clip8= pymupdf.Rect((385,830), (800, 1000))
    doc = pymupdf.open(pdf_file_name)
    "第一张照片提取"
    for z in range(len(doc)):
        doc = pymupdf.open(pdf_file_name)
        ''''批量处理基本数据'''
        page = doc[z]
        pix = page.get_pixmap(clip = clip1,dpi=300)
        print(f"-------第1张照片提取完毕------")
        pix.save(f"1.jpg")

    "第二张照片提取"
    for z in range(len(doc)):
        doc = pymupdf.open(pdf_file_name)
        ''''批量处理基本数据'''
        page = doc[z]
        pix = page.get_pixmap(clip = clip2,dpi=300)
        print(f"-------第2张照片提取完毕------")
        pix.save(f"2.jpg")

    "第三张照片提取"
    for z in range(len(doc)):
        doc = pymupdf.open(pdf_file_name)
        ''''批量处理基本数据'''
        page = doc[z]
        pix = page.get_pixmap(clip = clip3,dpi=300)
        print(f"-------第3张照片提取完毕------")
        pix.save(f"3.jpg")

    "第四张照片提取"
    for z in range(len(doc)):
        doc = pymupdf.open(pdf_file_name)
        ''''批量处理基本数据'''
        page = doc[z]
        pix = page.get_pixmap(clip = clip4,dpi=300)
        print(f"-------第4张照片提取完毕------")
        pix.save(f"4.jpg")

    "第五张照片提取"
    for z in range(len(doc)):
        doc = pymupdf.open(pdf_file_name)
        ''''批量处理基本数据'''
        page = doc[z]
        pix = page.get_pixmap(clip = clip5,dpi=300)
        print(f"-------第5张照片提取完毕------")
        pix.save(f"5.jpg")

    "第6张照片提取"
    for z in range(len(doc)):
        doc = pymupdf.open(pdf_file_name)
        ''''批量处理基本数据'''
        page = doc[z]
        pix = page.get_pixmap(clip = clip6,dpi=300)
        print(f"-------第6张照片提取完毕------")
        pix.save(f"6.jpg")

    "第7张照片提取"
    for z in range(len(doc)):
        doc = pymupdf.open(pdf_file_name)
        ''''批量处理基本数据'''
        page = doc[z]
        pix = page.get_pixmap(clip = clip7,dpi=300)
        print(f"-------第7张照片提取完毕------")
        pix.save(f"7.jpg")

    for z in range(len(doc)):
        doc = pymupdf.open(pdf_file_name)
        ''''批量处理基本数据'''
        page = doc[z]
        pix = page.get_pixmap(clip = clip8,dpi=300)
        print(f"-------第8张照片提取完毕------")
        pix.save(f"8.jpg")

    for z in range(len(doc)):
        '''单独处理特殊数据'''
        page = doc[z]
        print(z)
        pix = page.get_pixmap(clip=clip2_1, dpi=300)
        print(f"照片提取完毕")
        pix.save(f"2_1.jpg")
    # for i in range(24): #切出剩下的照片
    #     x = 60 + i*27.5
    #     y = 80 + i*27.5
    #     clip2 = pymupdf.Rect((x,157), (y, 270))
    #     doc = pymupdf.open(pdf_file_name)
    #     for z in range(len(doc)):
    #         page = doc[z]
    #         pix = page.get_pixmap(clip=clip2, dpi=300)
    #         print(f"第{i}张照片提取完毕")
    #         pix.save(f"./1/2_{i}.jpg")
# 设置图像路径



def qqk():
    content_list = []
    for i in range(1, 9):
        content = tup_shibie(f'{i}.jpg')
        if i == 2:
            content_child_list = content.split(' ')
            mo_list = ''
            power_list = ["团队领导能力", '人际关系能力', "辅导培养能力", "组织协调能力", "服务意识", "影响说服力",
                          "逻辑推理能力", "战略规划能力", "总结能力", "创新能力", "决策能力", "原则性", "自控能力",
                          "上进心", "坚韧性", "好胜心", "自信心", "大局观", "结果导向", "业务开拓能力", "尽责性",
                          "落地执行力", "细节处理能力", "灵活应变能力"]
            for x in range(len(content_child_list)):
                # print(x)
                try:
                    coo = "得分：" + str(content_child_list[x]) + "与得分对应的能力：" + str(power_list[x])
                    print(coo)
                except:
                    print("--->")
                    break
                mo_list = mo_list + coo
            content = mo_list
        print(f"-----正在识别第{i}个模块请稍等！---------")
        # print(content)
        content_list.append(content)
    """将生成的文件写入csv中"""
    print(content_list)
    csv_Writer.writerow(
        [content_list[0], content_list[1], content_list[2], content_list[3], content_list[4], content_list[5],
         content_list[6], content_list[7]])

def mian():
    for i in pdf_file_name:
        splie_pdf(i)
        qqk()


if __name__ == '__main__':
    i = input("请确定程序和对应的文件在同一目录下：确定就请输入1：")
    if i == '1':
        mian()
    else:
        print("请将文件和程序放置在同一目录！")



# # 导入CnOcr类
# from cnocr import CnOcr
# # 设置图像路径
# img_fp="./1.jpg"
# # 创建CnOcr对象
# ocr = CnOcr()
# # 读取图像
# out = ocr.ocr(img_fp)
# print(out)
# #返回列表类型[{},{}]